var express = require('express');
var router = express.Router();
const {
    Setting
} = require('../../models');
const {
    Op
} = require('sequelize');
const { success, error, notFound, formatPagination } = require('../../utils/response');
const { filterSettingBody, getPaginationParams } = require('../../utils/filter');

// 查询系统设置详情
/**
 * @api {get} /admin/settings 查询系统设置详情
 * @apiName GetArticleById
 * @apiGroup Articles
 * @apiVersion 1.0.0
 */
router.get('/', async function (req, res, next) {
    try {
        const setting = await Setting.findOne();
        if (!setting) {
            return res.status(404).json(notFound('系统设置'));
        }
        res.json(success(setting, '查询成功'));
    } catch (err) {
        res.json(error('查询失败', 500, err.message));
    }
});

// 更新系统设置
/**
 * @api {post} /admin/settings/update 更新系统设置
 * @apiName UpdateArticle
 * @apiGroup Articles
 * @apiVersion 1.0.0
 * 
 */
router.post('/update', async function (req, res, next) {
    try {
        const setting = await Setting.findOne();
        if (!setting) {
            return res.status(404).json(notFound('系统设置'));
        }
        const updateData = filterSettingBody(req.body);
        await setting.update(updateData);
        res.json(success(setting, '更新成功'));
    } catch (err) {
        if (err.name === 'SequelizeValidationError') {
            const errors = err.errors.map(e => e.message);
            return res.status(400).json(error('更新失败', 400, errors));
        }
        res.json(error('更新失败'));
    }
});
module.exports = router;